home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume25 / pty4 / part08 < prev    next >
Encoding:
Text File  |  1992-02-18  |  42.3 KB  |  1,334 lines

  1. Newsgroups: comp.sources.unix
  2. From: brnstnd@nyu.edu (Dan Bernstein)
  3. Subject: v25i134: Generalized interface to pseudo-tty devices, Part08/09
  4. Sender: unix-sources-moderator@pa.dec.com
  5. Approved: vixie@pa.dec.com
  6.  
  7. Submitted-By: brnstnd@nyu.edu (Dan Bernstein)
  8. Posting-Number: Volume 25, Issue 134
  9. Archive-Name: pty4/part08
  10.  
  11. #! /bin/sh
  12. # This is a shell archive.  Remove anything before this line, then unpack
  13. # it by saving it into a file and typing "sh file".  To overwrite existing
  14. # files, type "sh file -c".  You can also feed this as standard input via
  15. # unshar, or by typing "sh <file", e.g..  If this archive is complete, you
  16. # will see the following message at the end:
  17. #        "End of archive 8 (of 9)."
  18. # Contents:  ptymaster.c radixsort.c
  19. # Wrapped by vixie@cognition.pa.dec.com on Wed Feb 19 13:35:06 1992
  20. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  21. if test -f 'ptymaster.c' -a "${1}" != "-c" ; then 
  22.   echo shar: Will not clobber existing file \"'ptymaster.c'\"
  23. else
  24. echo shar: Extracting \"'ptymaster.c'\" \(20275 characters\)
  25. sed "s/^X//" >'ptymaster.c' <<'END_OF_FILE'
  26. X#include <sys/types.h>
  27. X#include <sys/wait.h>
  28. X#include <sys/time.h>
  29. X#include <sys/resource.h>
  30. X#include <signal.h>
  31. X#include <errno.h>
  32. extern int errno;
  33. X#include "sigsched.h"
  34. X#include "ralloc.h"
  35. X#include "config/ttyopts.h"
  36. X#include "config/ptylongname.h"
  37. X#include "sesslog.h"
  38. X#include "sessconnlog.h"
  39. X#include "ptyget.h"
  40. X#include "ptymisc.h"
  41. X#include "ptyerr.h"
  42. X#include "ptytty.h"
  43. X#include "ptycomm.h"
  44. X#include "ptymaster.h"
  45. X
  46. X/*
  47. If you don't believe that sigsched makes this incredibly easy to write,
  48. try writing it without sigsched. Then try understanding what you wrote.
  49. X
  50. Apologies in advance to Billy Joel.
  51. X*/
  52. X
  53. X#define PTYBUFSIZE 16384
  54. X
  55. char inbuf[PTYBUFSIZE];
  56. static int inbufwrite = 0;
  57. static int inbufread = 0;
  58. char outbuf[PTYBUFSIZE];
  59. static int outbufwrite = 0;
  60. static int outbufread = 0;
  61. X
  62. static char longname[PTYLONGNAMELEN] = { 0 };
  63. X
  64. static struct sessconnlog scl;
  65. static int remotelen;
  66. static char remote[SESSCONNLOG_REMOTELEN];
  67. static char *musername;
  68. X
  69. static int mflagreading;
  70. static int mflagsession;
  71. static int mflagxflowctl;
  72. static int mfdcomm;
  73. static int mfdmty;
  74. static int mfdsty;
  75. static int muid = -1;
  76. static char mext[2];
  77. static int mslavepid = -1;
  78. X
  79. static int fdctrlr = -1;
  80. static int fdsigler;
  81. X/* to insure yourself you got to provide communication constantly... */
  82. static int fdsig2us;
  83. static int fdi;
  84. static int fdo;
  85. static int flagwatchchld;
  86. static int flagstopped;
  87. X
  88. static char recoext[2];
  89. X/* this is a violation of modularity, but even after the sigler */
  90. X/* knows what recoext is, we may have to report it to ctrlr, so we can't */
  91. X/* just forget about it XXX: or should we ask sigler dynamically? no! */
  92. X
  93. static int mfdpreco;
  94. static int flagpreco;
  95. X
  96. X/* This is a kludge to deal with fd passing bugs (particularly under SunOS). */
  97. X/* It's also a sanity check. */
  98. void closeallbut()
  99. X{
  100. X int i;
  101. X
  102. X i = getdtablesize();
  103. X while (i--)
  104. X  {
  105. X   if (
  106. X   (i != mfdcomm)
  107. X&& (i != mfdmty)
  108. X&& (i != mfdsty)
  109. X&& (i != fdctrlr)
  110. X&& (i != fdsigler)
  111. X&& (i != fdsig2us)
  112. X&& (i != fdi)
  113. X&& (i != fdo)
  114. X&& (i != mfdpreco)
  115. X      )
  116. X    {
  117. X     close(i);
  118. X    }
  119. X  }
  120. X}
  121. X
  122. X#define verbose 0,
  123. X
  124. static void saytasig(c0,c1,c2,c3) int c0; int c1; int c2; int c3;
  125. X{
  126. X char c[4]; c[0] = c0; c[1] = c1; c[2] = c2; c[3] = c3;
  127. X verbose("master telling sigler %c %d %d %d",c0,c1,c2,c3);
  128. X if (fdsigler == -1)
  129. X   return;
  130. X /* tell her all your crazy dreams... */
  131. X bwrite(fdsigler,c,4); /* XXX: error checks? */
  132. X}
  133. X
  134. static void childdead()
  135. X{
  136. X verbose("master entering childdead");
  137. X /* We could check specially for final output here, but since */
  138. X /* there's no way we can know when it's all done, we don't bother. */
  139. X if (fdsigler != -1)
  140. X   ; /* no need for further notification or explicit EOF */
  141. X if (mslavepid != -1)
  142. X  {
  143. X   struct sesslog sl;
  144. X   long t;
  145. X   t = now();
  146. X   sessconnlog_fill(&scl,mext,"",0,t);
  147. X   sesslog_fill(&sl,mext,musername,muid,0,t);
  148. X   if (fdsigler != -1)
  149. X     sessconnlog(&scl); /* XXX: failure? */
  150. X   sesslog(&sl); /* XXX: failure? */
  151. X   utmp_off(mext,"",t); /* XXX: failure? */
  152. X   wtmp_off(mext,"",t); /* XXX: failure? */
  153. X   ungetpty(mfdmty,mfdsty,mext); /* XXX: failure? */
  154. X   mslavepid = -1; /* JIC */
  155. X   if (mfdcomm != -1)
  156. X    {
  157. X     if (comm_unlink(mext,muid) == -1)
  158. X       ; /* if it fails, who cares? */
  159. X     close(mfdcomm); /* goodbye, cruel world */
  160. X     mfdcomm = -1;
  161. X    }
  162. X   ss_unforcewait();
  163. X  }
  164. X}
  165. X
  166. static void contchild()
  167. X{
  168. X if (mslavepid != -1)
  169. X  {
  170. X   if (kill(mslavepid,SIGCONT) == -1) /* XXX: when would this work? */
  171. X    {
  172. X     int pgrp;
  173. X     pgrp = getpgrp(mslavepid);
  174. X     if (pgrp > 0)
  175. X       killpg(pgrp,SIGCONT);
  176. X       /* XXX: errors? */
  177. X    }
  178. X  }
  179. X flagstopped = 0;
  180. X disp_flagstopped();
  181. X}
  182. X
  183. static void disconnect()
  184. X{
  185. X verbose("master disconnecting");
  186. X /* oh listen boy */
  187. X /* i'm sure you think you got it all under control... */
  188. X saytasig('d',0,0,0);
  189. X
  190. X if (fdsigler != -1)
  191. X  {
  192. X   long t;
  193. X   t = now();
  194. X   sessconnlog_fill(&scl,mext,"",1/*XXX*/,t);
  195. X   sessconnlog(&scl); /* XXX: failure? */
  196. X  }
  197. X
  198. X if (fdsigler != -1) { close(fdsigler); fdsigler = -1; }
  199. X if (fdsig2us != -1) { close(fdsig2us); fdsig2us = -1; }
  200. X if (fdi != -1) { close(fdi); fdi = -1; }
  201. X if (fdo != -1) { close(fdo); fdo = -1; }
  202. X flagwatchchld = 0;
  203. X recoext[0] = recoext[1] = 0;
  204. X disp_fdsigler();
  205. X disp_fdsig2us();
  206. X disp_flagwatchchld();
  207. X if (!mflagsession)
  208. X   childdead();
  209. X   /* ... and though you may not have done anything */
  210. X   /* will that be consolation when she's gone? ... */
  211. X closeallbut();
  212. X}
  213. X
  214. static int reconnect()
  215. X{
  216. X verbose("master starting reconnect");
  217. X
  218. X closeallbut();
  219. X /* assumes fdsigler, fdsig2us, fdi, fdo all -1 */
  220. X if ((fdsigler = comm_getfd(fdctrlr)) == -1)
  221. X  {
  222. X   verbose("master getting sigler failed");
  223. X   return -1; }
  224. X if ((fdsig2us = comm_getfd(fdctrlr)) == -1)
  225. X  {
  226. X   verbose("master getting fdsig2us failed");
  227. X   close(fdsigler); fdsigler = -1; return -1; }
  228. X if ((fdi = comm_getfd(fdctrlr)) == -1)
  229. X  {
  230. X   verbose("master getting fdi failed");
  231. X   close(fdsigler); close(fdsig2us); fdsigler = fdsig2us = -1; return -1; }
  232. X if ((fdo = comm_getfd(fdctrlr)) == -1)
  233. X  {
  234. X   verbose("master getting fdo failed");
  235. X   close(fdsigler); close(fdsig2us); close(fdi);
  236. X   fdsigler = fdsig2us = fdi = -1; return -1; }
  237. X
  238. X verbose("master okay fds on reconnect %d %d %d %d",fdsigler,fdsig2us,fdi,fdo);
  239. X if (bread(fdctrlr,(char *) &mflagreading,sizeof(int)) < sizeof(int))
  240. X  { close(fdsigler); close(fdsig2us); close(fdi); close(fdo);
  241. X   fdsigler = fdsig2us = fdi = fdo = -1; return -1; }
  242. X if (bread(fdctrlr,(char *) &remotelen,sizeof(int)) < sizeof(int)
  243. X    || (remotelen > SESSCONNLOG_REMOTELEN))
  244. X  { close(fdsigler); close(fdsig2us); close(fdi); close(fdo);
  245. X   fdsigler = fdsig2us = fdi = fdo = -1; return -1; }
  246. X if (bread(fdctrlr,remote,remotelen) < remotelen)
  247. X  { close(fdsigler); close(fdsig2us); close(fdi); close(fdo);
  248. X   fdsigler = fdsig2us = fdi = fdo = -1; return -1; }
  249. X
  250. X /* log stuff... */
  251. X sessconnlog_fill(&scl,mext,remote,-1/*XXX*/,now());
  252. X if (sessconnlog(&scl) == -1)
  253. X   ; /*XXX: sessconn write failed; do we care?*/
  254. X
  255. X closeallbut();
  256. X
  257. X verbose("master succeeded on reconnect %d",mflagreading);
  258. X contchild(); /* XXX */
  259. X flagwatchchld = 1;
  260. X disp_fdsigler();
  261. X disp_fdsig2us();
  262. X disp_flagwatchchld();
  263. X disp_mflagreading();
  264. X if (flagpreco) /* talk to me if you don't understand this */
  265. X  {
  266. X   flagpreco = 0;
  267. X   /* cause now and then she'll get to worrying */
  268. X   /* just because you haven't spoken for so long... */
  269. X   if (write(mfdpreco,"k",1) == -1)
  270. X     ; /* pipe might be broken if child has somehow been killed; */
  271. X       /* that's okay, we'll get SIGCHLD in a few moments */
  272. X   close(mfdpreco);
  273. X   mfdpreco = -1;
  274. X  }
  275. X return 0;
  276. X}
  277. X
  278. static void sigchld(n)
  279. int n;
  280. X{
  281. X int w;
  282. X int pid;
  283. X
  284. X verbose("master entering sigchld");
  285. X while ((pid = wait3(&w,WNOHANG | WUNTRACED,(struct rusage *) 0)) > 0)
  286. X   /* it'd be very weird if wait3 equalled 0 */ 
  287. X   if (pid == mslavepid)
  288. X    {
  289. X     verbose("master sees pid %d",pid);
  290. X#define PWIFSTOPPED(s) (((s) & 0177) == 0177)
  291. X#define PWSTOPSIG(s) ((s) >> 8) /* only defined if PWIFSTOPPED */
  292. X     if (PWIFSTOPPED(w))
  293. X      {
  294. X       flagstopped = 1;
  295. X       /* just a word or two that she gets from you */
  296. X       /* could be the difference that it makes... */
  297. X       saytasig('z',PWSTOPSIG(w),0,0);
  298. X       disp_flagstopped();
  299. X      }
  300. X     else
  301. X      {
  302. X#define PWIFEXITED(s) (!((s) & 0177))
  303. X#define PWEXITSTATUS(s) ((s) >> 8)
  304. X#define PWTERMSIG(s) ((s) & 0177)
  305. X#define PWCOREDUMP(s) ((s) & 0200)
  306. X       if (PWIFEXITED(w))
  307. X     /* tell her about it... */
  308. X         saytasig('e',PWEXITSTATUS(w),0,0);
  309. X       else
  310. X     /* tell her everything you feel... */
  311. X     saytasig('s',PWTERMSIG(w),PWCOREDUMP(w),0);
  312. X       childdead();
  313. X      }
  314. X    }
  315. X}
  316. static int schedsigchld = 0;
  317. static void cksigchld()
  318. X{
  319. X if (!schedsigchld && flagwatchchld && !outbufread)
  320. X  { ss_sched(ss_signal(SIGCHLD),sigchld,0); schedsigchld = 1; return; }
  321. X if (schedsigchld && (!flagwatchchld || outbufread))
  322. X  { ss_unsched(ss_signal(SIGCHLD),sigchld,0); schedsigchld = 0; }
  323. X}
  324. X
  325. static void doacceptfdctrlr(n)
  326. int n;
  327. X{
  328. X fdctrlr = comm_accept(mfdcomm);
  329. X disp_fdctrlr();
  330. X}
  331. static int schedacceptfdctrlr = 0;
  332. static void ckacceptfdctrlr()
  333. X{
  334. X if (!schedacceptfdctrlr && (fdctrlr == -1))
  335. X  {
  336. X   ss_sched(ss_sigread(mfdcomm),doacceptfdctrlr,0); schedacceptfdctrlr = 1;
  337. X   return;
  338. X  }
  339. X if (schedacceptfdctrlr && (fdctrlr != -1))
  340. X  { ss_unsched(ss_sigread(mfdcomm),doacceptfdctrlr,0); schedacceptfdctrlr = 0; }
  341. X}
  342. X
  343. static void doreadfdctrlr(n)
  344. int n;
  345. X{
  346. X int r;
  347. X char mess[1];
  348. X int foo;
  349. X
  350. X verbose("master entering readfdctrlr");
  351. X r = read(fdctrlr,mess,1);
  352. X verbose("master readfdctrlr %d %c",r,mess[0]);
  353. X if (r <= 0) /* bye bye */
  354. X  {
  355. X   close(fdctrlr); fdctrlr = -1; disp_fdctrlr(); return;
  356. X  }
  357. X switch(mess[0]) /* XXX: we tacitly assume these writes will be atomic */
  358. X  {
  359. X   case 'a': /* are you there? */
  360. X     switch(mslavepid % 3)
  361. X      {
  362. X       case 0: bwrite(fdctrlr,"(nope)",6); break;
  363. X       case 1: bwrite(fdctrlr,"a_y_t?",6); break;
  364. X       default: bwrite(fdctrlr,"maybe.",6); break;
  365. X      }
  366. X     break;
  367. X   case 'e': /* short name? */
  368. X     bwrite(fdctrlr,mext,2);
  369. X     break;
  370. X   case 'l': /* long name? */
  371. X     bwrite(fdctrlr,"longnm",6);
  372. X     bwrite(fdctrlr,longname,sizeof(longname));
  373. X     break;
  374. X   case 'L': /* set long name to this: */
  375. X     bread(fdctrlr,longname,sizeof(longname)); /* XXX: error checking? */
  376. X     bwrite(fdctrlr,"thanks",6);
  377. X     break;
  378. X   case 'C': /* are you connected? */
  379. X     if (fdsigler == -1)
  380. X       bwrite(fdctrlr,"noaose",6);
  381. X     else
  382. X       bwrite(fdctrlr,"owuno?",6);
  383. X     break;
  384. X   case 'p': /* what's your pid? */
  385. X     foo = getpid();
  386. X     bwrite(fdctrlr,(char *) &foo,sizeof(foo));
  387. X     break;
  388. X   case 'P': /* what's your slave pid? */
  389. X     bwrite(fdctrlr,(char *) &mslavepid,sizeof(mslavepid));
  390. X     break;
  391. X   case 'D': /* do you allow disconnects? */
  392. X     bwrite(fdctrlr,(char *) &mflagsession,sizeof(mflagsession));
  393. X     break;
  394. X   case 'k': /* sesskill */
  395. X     saytasig('k',0,0,0);
  396. X     bwrite(fdctrlr,"<poof>",6);
  397. X     childdead();
  398. X     break;
  399. X   case 'd': /* disconnect */
  400. X     if (mflagsession)
  401. X       if (fdsigler != -1)
  402. X    {
  403. X     disconnect();
  404. X     bwrite(fdctrlr,"yessir",6);
  405. X    }
  406. X       else
  407. X     bwrite(fdctrlr,"no-op!",6);
  408. X     else
  409. X       /* you're a big boy now and you'll never let her go */
  410. X       /* but that's just the kind of thing she ought to know... */
  411. X       bwrite(fdctrlr,"kinky!",6);
  412. X     break;
  413. X   case 'r': /* reconnect---including initial connection */
  414. X     if (fdsigler == -1)
  415. X      {
  416. X       /* let her know you need her */
  417. X       /* let her know how much she means... */
  418. X       bwrite(fdctrlr,"shrtng",6);
  419. X       if (reconnect() == -1)
  420. X    {
  421. X     bwrite(fdctrlr,"damn! ",6); /*XXXXXXX*/
  422. X     closeallbut();
  423. X    }
  424. X       else
  425. X         bwrite(fdctrlr,"phew! ",6);
  426. X      }
  427. X     else
  428. X       bwrite(fdctrlr,"no-go!",6);
  429. X     break;
  430. X   case 's': /* recoset */
  431. X     if (fdsigler != -1)
  432. X      {
  433. X       /* XXX: should ack first */
  434. X       bread(fdctrlr,recoext,2); /* XXX: error checks? */
  435. X       /* when she can't be with you tell her you wish you were there... */
  436. X       saytasig('r',recoext[0],recoext[1],0);
  437. X       bwrite(fdctrlr,"sglrok",6);
  438. X      }
  439. X     else
  440. X       bwrite(fdctrlr,"nosglr",6);
  441. X     break;
  442. X   case 'S': /* report latest recoset */
  443. X     bwrite(fdctrlr,"latest",6);
  444. X     bwrite(fdctrlr,recoext,2);
  445. X     break;
  446. X   case 'Z': /* suspend */
  447. X     /* XXXX: not supported yet; fall through */
  448. X   /* XXX: resume? */
  449. X   /* XXX: ioctl? particular ioctls? */
  450. X   default:
  451. X     bwrite(fdctrlr,"nosupp",6);
  452. X     break;
  453. X  }
  454. X verbose("master exiting readfdctrlr");
  455. X}
  456. static ss_sig *sigreadfdctrlr;
  457. static void ckreadfdctrlr()
  458. X{
  459. X if (!sigreadfdctrlr && (fdctrlr != -1))
  460. X  { ss_sched(sigreadfdctrlr = ss_sigread(fdctrlr),doreadfdctrlr,0); return; }
  461. X if (sigreadfdctrlr && (fdctrlr == -1))
  462. X  { ss_unsched(sigreadfdctrlr,doreadfdctrlr,0); sigreadfdctrlr = 0; }
  463. X}
  464. X
  465. static void doreadsig2us(n)
  466. int n;
  467. X{
  468. X int r;
  469. X char sigsez[1];
  470. X#ifdef TTY_WINDOWS
  471. X struct ttywin twi;
  472. X struct ttymodes tmoold;
  473. X struct ttymodes tmonew;
  474. X#endif
  475. X
  476. X verbose("master entering readsig2us");
  477. X /* every day before you leave */
  478. X /* pay her some attention */
  479. X /* give her something to believe... */
  480. X r = read(fdsig2us,sigsez,1);
  481. X verbose("master readsig2us %d %c",r,sigsez[0]);
  482. X if (r == -1)
  483. X   disconnect(); /*XXX: should we try to handle errors better? */
  484. X else if (!r)
  485. X   disconnect(); /* if it weren't for this, we'd never see sigler die! */
  486. X else
  487. X   switch(sigsez[0])
  488. X    {
  489. X     case 'H': /* hangup */
  490. X       disconnect();
  491. X       break;
  492. X     case 'C': /* continue */
  493. X       contchild();
  494. X       break;
  495. X     case 'W': /* WINCH */
  496. X#ifdef TTY_WINDOWS
  497. X       bread(fdsig2us,(char *) &twi,sizeof(twi)); /* XXX: error checks? */
  498. X       if (tty_getmodes(mfdsty,&tmoold) == 0)
  499. X    {
  500. X         /* XXX: race! race! race! */
  501. X         tty_copymodes(&tmonew,&tmoold);
  502. X         tty_win2modes(&twi,&tmonew);
  503. X         if (tty_modifymodes(mfdsty,&tmonew,&tmoold) == -1)
  504. X       ; /* who cares? */
  505. X    }
  506. X#endif
  507. X       break;
  508. X     default:
  509. X       break; /* XXX: nothing we can reasonably do */
  510. X    }
  511. X verbose("master exiting readsig2us");
  512. X}
  513. static ss_sig *sigreadsig2us;
  514. static void ckreadsig2us()
  515. X{
  516. X if (!sigreadsig2us && (fdsig2us != -1))
  517. X  { ss_sched(sigreadsig2us = ss_sigread(fdsig2us),doreadsig2us,0); return; }
  518. X if (sigreadsig2us && (fdsig2us == -1))
  519. X  { ss_unsched(sigreadsig2us,doreadsig2us,0); sigreadsig2us = 0; }
  520. X}
  521. X
  522. static void doreadin(n)
  523. int n;
  524. X{
  525. X int r;
  526. X
  527. X verbose("master entering readin");
  528. X /* XXX: sanity checks, like !mflagreading? */
  529. X
  530. X /* XXX: Warning! We're manipulating an outside descriptor! */
  531. X r = read(fdi,inbuf + inbufread,sizeof(inbuf) - inbufread);
  532. X /* but a girl like that won't tell you what you should do... */
  533. X if (r == -1)
  534. X   switch(errno) { case EINTR: case EWOULDBLOCK: break;
  535. X     default: disconnect(); /*XXXX*/ }
  536. X else if (!r)
  537. X  {
  538. X   /* XXX: this EOF handling is all rather slimy */
  539. X   if (mflagsession)
  540. X     disconnect();
  541. X   else
  542. X    {
  543. X     mflagreading = 0;
  544. X     disp_mflagreading();
  545. X    }
  546. X  }
  547. X else { inbufread += r; disp_inbufread(); }
  548. X verbose("master exiting readin");
  549. X}
  550. static ss_sig *sigreadin = 0;
  551. static void ckreadin()
  552. X{
  553. X if (!sigreadin && (fdsigler != -1) && (inbufread < sizeof(inbuf))
  554. X   && mflagreading && !flagstopped)
  555. X  { ss_sched(sigreadin = ss_sigread(fdi),doreadin,0); return; }
  556. X if (sigreadin && ((fdsigler == -1) || (inbufread == sizeof(inbuf))
  557. X   || !mflagreading || flagstopped))
  558. X  { ss_unsched(sigreadin,doreadin,0); sigreadin = 0; }
  559. X}
  560. X
  561. static void dowritein(n)
  562. int n;
  563. X{
  564. X int w;
  565. X
  566. X verbose("master entering writein");
  567. X if (mflagxflowctl)
  568. X  {
  569. X   if (tty_spaceleft(mfdsty) < 128)
  570. X     return;
  571. X   /* XXX: this busy-loops! */
  572. X  }
  573. X if (mflagxflowctl && (inbufread - inbufwrite > 128))
  574. X   w = write(mfdmty,inbuf + inbufwrite,128);
  575. X else
  576. X   w = write(mfdmty,inbuf + inbufwrite,inbufread - inbufwrite);
  577. X if (w == -1)
  578. X   switch(errno) { case EINTR: case EWOULDBLOCK: break;
  579. X     default: ; /*XXXX*/ }
  580. X else
  581. X  {
  582. X   inbufwrite += w;
  583. X   if (inbufwrite == inbufread)
  584. X    { inbufwrite = inbufread = 0; disp_inbufread(); }
  585. X   disp_inbufwrite();
  586. X  }
  587. X verbose("master exiting writein");
  588. X}
  589. static ss_sig *sigwritein = 0;
  590. static void ckwritein()
  591. X{
  592. X if (!sigwritein && (mfdmty != -1) && (inbufwrite < inbufread))
  593. X  { ss_sched(sigwritein = ss_sigwrite(mfdmty),dowritein,0); return; }
  594. X if (sigwritein && ((mfdmty == -1) || (inbufwrite == inbufread)))
  595. X  { ss_unsched(sigwritein,dowritein,0); sigwritein = 0; }
  596. X}
  597. X
  598. static void doreadout(n)
  599. int n;
  600. X{
  601. X int r;
  602. X verbose("master entering doreadout");
  603. X
  604. X r = read(mfdmty,outbuf + outbufread,sizeof(outbuf) - outbufread);
  605. X verbose("master doreadout: %d",r);
  606. X if (r == -1)
  607. X   switch(errno) { case EINTR: case EWOULDBLOCK: break;
  608. X     default: ; /*XXXX*/ }
  609. X else if (!r)
  610. X   ; /* XXX: EOF on a pty? utterly impossible */
  611. X else { outbufread += r; disp_outbufread(); }
  612. X}
  613. static ss_sig *sigreadout = 0;
  614. static void ckreadout()
  615. X{
  616. X if (!sigreadout && (mfdmty != -1) && (outbufread < sizeof(outbuf)))
  617. X  { ss_sched(sigreadout = ss_sigread(mfdmty),doreadout,0); return; }
  618. X if (sigreadout && ((mfdmty == -1) || (outbufread == sizeof(outbuf))))
  619. X  { ss_unsched(sigreadout,doreadout,0); sigreadout = 0; }
  620. X}
  621. X
  622. static void dowriteout(n)
  623. int n;
  624. X{
  625. X int w;
  626. X verbose("master entering writeout");
  627. X /* XXX: Warning! We're manipulating an outside descriptor! */
  628. X w = write(fdo,outbuf + outbufwrite,outbufread - outbufwrite);
  629. X if (w == -1)
  630. X   switch(errno) { case EINTR: case EWOULDBLOCK: break;
  631. X   case EPIPE: disconnect(); /* ``the master treats PIPE like EOF'' */
  632. X   default: disconnect(); /*XXXX*/ }
  633. X else
  634. X  {
  635. X   outbufwrite += w;
  636. X   if (outbufwrite == outbufread)
  637. X    { outbufwrite = outbufread = 0; disp_outbufread(); }
  638. X   disp_outbufwrite();
  639. X  }
  640. X verbose("master exiting writeout");
  641. X}
  642. static ss_sig *sigwriteout = 0;
  643. static void ckwriteout()
  644. X{
  645. X if (!sigwriteout && (fdsigler != -1) && (outbufwrite < outbufread) && !flagstopped)
  646. X  { ss_sched(sigwriteout = ss_sigwrite(fdo),dowriteout,0); return; }
  647. X if (sigwriteout && ((fdsigler == -1) || (outbufwrite == outbufread) || flagstopped))
  648. X  { ss_unsched(sigwriteout,dowriteout,0); sigwriteout = 0; }
  649. X}
  650. X
  651. X/*
  652. We have ck{acceptfdctrlr,readfdctrlr,readin,writein,readout,writeout,
  653. readsig2us,sigchld}.
  654. When flagstopped changes, which ck*() have to be called?
  655. The dispatchers know. disp_flagstopped, for instance.
  656. It'd be interesting to see a programming language where these could
  657. be generated automatically---it was semi-automatic by hand.
  658. Of course, you could also look at this as an optimization problem...
  659. X*/
  660. X
  661. X/* these aren't void 'cause forward static declarations are unportable */
  662. static disp_mflagreading() { ckreadin(); }
  663. static disp_flagstopped() { ckreadin(); ckwriteout(); }
  664. static disp_flagwatchchld() { cksigchld(); }
  665. static disp_mfdmty() { ckwritein(); ckreadout(); } /* ever? */
  666. static disp_fdctrlr() { ckacceptfdctrlr(); ckreadfdctrlr(); }
  667. static disp_fdsigler() { ckreadin(); ckwriteout(); }
  668. static disp_fdsig2us() { ckreadsig2us(); }
  669. static disp_inbufread() { ckreadin(); ckwritein(); }
  670. static disp_inbufwrite() { ckwritein(); }
  671. static disp_outbufread() { ckreadout(); ckwriteout(); cksigchld(); }
  672. static disp_outbufwrite() { ckwriteout(); }
  673. X
  674. static void disp() { ckreadin(); ckwriteout(); ckreadout(); cksigchld();
  675. X  ckacceptfdctrlr(); ckreadfdctrlr(); ckwritein(); ckreadsig2us(); }
  676. X
  677. X/*
  678. Signal handling:
  679. X
  680. fdctrlr == -1 and mfdcomm readable: accept fdctrlr
  681. fdctrlr != -1 and fdctrlr readable: read command (or close)
  682. fdsig2us != -1 and fdsig2us readable: read stuff from sigler
  683. fdsigler != -1 and fdi readable and ibuf okay and reading and !stopped: read
  684. fdsigler != -1 and fdo readable and obuf nonempty and !stopped: write
  685. mfdmty != -1 and mfdmty readable and obuf okay: read from mfdmty into buffer
  686. mfdmty != -1 and mfdmty writable and ibuf nonempty: write
  687. X
  688. CHLD, while flagwatchchld: if exited, tell sigler exit status, and exit
  689. X  if stopped: if sigler, tell sigler to stop, else remember stop
  690. HUP, TSTP, TTIN, TTOU, WINCH, INT, QUIT: ignore
  691. PIPE: ignore (we handle EPIPE on write())
  692. X
  693. X*/
  694. X
  695. void master(fdcomm,fdmty,fdsty,ext,uid,pid,flagsession,fdpreco,username,flagxflowctl)
  696. int fdcomm;
  697. int fdmty;
  698. int fdsty;
  699. char *ext;
  700. int uid;
  701. int pid; /* pid of child */
  702. int flagsession;
  703. int fdpreco;
  704. char *username;
  705. int flagxflowctl;
  706. X{
  707. X musername = username;
  708. X mflagsession = flagsession;
  709. X mflagxflowctl = flagxflowctl;
  710. X mflagreading = 0; /* will change with flagsigler */
  711. X mfdcomm = fdcomm;
  712. X mfdmty = fdmty;
  713. X mfdsty = fdsty;
  714. X muid = uid;
  715. X mext[0] = ext[0];
  716. X mext[1] = ext[1];
  717. X mslavepid = pid;
  718. X flagstopped = 0;
  719. X fdsigler = -1;
  720. X fdsig2us = -1;
  721. X flagwatchchld = 0;
  722. X fdi = -1;
  723. X fdo = -1;
  724. X flagpreco = 1;
  725. X mfdpreco = fdpreco;
  726. X
  727. X recoext[0] = recoext[1] = 0;
  728. X
  729. X ss_forcewait(); /* to be turned off exactly once, namely when child exits */
  730. X
  731. X rallocneverfail(childdead); /* XXX: this is, arguably, suboptimal */
  732. X
  733. X disp(); /* starts up slave I/O and CHLD handler */
  734. X/*
  735. We're already ignoring HUP, INT, TSTP, TTOU, TTIN, WINCH, QUIT, PIPE.
  736. X
  737. Other signals to worry about: URG and IO are ignored by default; fine.
  738. USR1 and USR2 should never be generated.
  739. TERM should never be generated.
  740. X
  741. The user can arrange for XCPU, XFSZ, PROF, VTALRM, and ALRM to be sent:
  742. X*/
  743. X signal(SIGXCPU,SIG_IGN); /* XXX */
  744. X signal(SIGXFSZ,SIG_IGN); /* we'll get notice on write() */
  745. X signal(SIGALRM,SIG_IGN);
  746. X signal(SIGVTALRM,SIG_IGN);
  747. X signal(SIGPROF,SIG_IGN); /* and if we're being profiled, too bad! */
  748. X
  749. X signal(SIGTERM,SIG_IGN); /* XXX */
  750. X signal(SIGUSR1,SIG_IGN); /* XXX */
  751. X signal(SIGUSR2,SIG_IGN); /* XXX */
  752. X
  753. X closeallbut();
  754. X}
  755. END_OF_FILE
  756. if test 20275 -ne `wc -c <'ptymaster.c'`; then
  757.     echo shar: \"'ptymaster.c'\" unpacked with wrong size!
  758. fi
  759. # end of 'ptymaster.c'
  760. fi
  761. if test -f 'radixsort.c' -a "${1}" != "-c" ; then 
  762.   echo shar: Will not clobber existing file \"'radixsort.c'\"
  763. else
  764. echo shar: Extracting \"'radixsort.c'\" \(20057 characters\)
  765. sed "s/^X//" >'radixsort.c' <<'END_OF_FILE'
  766. X/* radixsort.c, radixsort.h: linear-per-byte in-memory string sort
  767. Daniel J. Bernstein, brnstnd@nyu.edu; Keith Bostic, bostic@ucbvax.berkeley.edu.
  768. No dependencies.
  769. Requires malloc, free, bcopy, bzero. Can use -DUCHAR_MAX.
  770. X10/5/91 DJB: Made c static, added ctr.
  771. X7/23/91 DJB: Baseline. radixsort/DJB 3.0. See bottom for BSD copyright.
  772. No known patent problems.
  773. X
  774. Documentation in radixsort.3, portions based on BSD documentation.
  775. X
  776. History: I discovered adaptive distribution sort in 1987. (I haven't
  777. published a paper on it---it's too trivial for that---though I did
  778. mention it in a letter to Knuth.) It grew out of a suggestion quoted in
  779. Knuth's section on quicksort et al., volume 3, page 128: ``John McCarthy
  780. has suggested setting K \approx (u + v)/2, if all keys are known to lie
  781. between u and v.'' What's the biggest problem with MSD radix sort? You
  782. can waste lots of time considering ranges of keys that don't even exist!
  783. In distribution sort, however, you usually start by finding the minimum
  784. and maximum keys. Here McCarthy's suggestion pops in. To sort a pile of
  785. floating-point numbers, find their minimum and maximum, divide the
  786. interval evenly into n subintervals, and split the numbers into piles by
  787. interval just as in MSD radix sort. Just as in quicksort, stop splitting
  788. when a pile can be sorted efficiently by a small-scale method. That's
  789. adaptive distribution sort, and it turns out to be hellishly fast for
  790. sorting floating-point data. The credit really belongs with McCarthy---I
  791. only generalized from 2 to n.
  792. X
  793. Adaptive distribution sort can be applied to strings, too: find the
  794. first character where two strings in the pile differ, and distribute on
  795. that character. There's no fine line between adaptive distribution sort
  796. and MSD radix sort, but in any case you get a big speed boost from
  797. sorting small piles by a small-scale method. See especially Knuth,
  798. exercise 5.2.5-10.
  799. X
  800. Computer scientists should note that this method is linear in the number
  801. of bytes being sorted. Sometime in 1989, as I recall, I saw a notice
  802. that someone had discovered an o(n log n) method of sorting n integers.
  803. The method depended on all sorts of weid bit manipulations and was
  804. utterly impractical. As the integers had to be short anyway, MSD radix
  805. sort worked in O(n) time. My guess is that most computer scientists
  806. don't learn about MSD radix sort (and hence don't know that sorting is
  807. linear-per-byte) because it's widely seen as having too big a constant
  808. factor to be practical. This radixsort() is a constructive proof that
  809. the opposite is true.
  810. X
  811. I ended up sending this code to Berkeley. Keith Bostic cleaned it up,
  812. fixed a few bugs, added a shell sort for the small case, and did several
  813. helpful optimizations. radixsort() will be part of BSD 4.4. I took back
  814. his version and modified it to what you see below. Among other things, I
  815. ported it from ANSI C back to the rest of the world, cleaned up some of
  816. the comments, added a proof that part of the method actually works,
  817. added the radixsort5(), radixsort7(), and radixsort3() variants,
  818. restored the original indentation, fixed an overly conservative estimate
  819. of the necessary stack size, and plugged a memory leak.
  820. X*/
  821. X
  822. X#define blob unsigned char /* technically, shouldn't be typedefed */
  823. X
  824. X/* KB says:
  825. X * __rspartition is the cutoff point for a further partitioning instead
  826. X * of a shellsort.  If it changes check __rsshell_increments.  Both of
  827. X * these are exported, as the best values are data dependent.
  828. X */
  829. X#ifndef NPARTITION
  830. X#define    NPARTITION 40
  831. X#endif
  832. int __rspartition = NPARTITION;
  833. int __rsshell_increments[] = { 4, 1, 0, 0, 0, 0, 0, 0 };
  834. X
  835. X/* KB says:
  836. X * Shellsort (diminishing increment sort) from Data Structures and
  837. X * Algorithms, Aho, Hopcraft and Ullman, 1983 Edition, page 290;
  838. X * see also Knuth Vol. 3, page 84. The increments are selected from
  839. X * formula (8), page 95. Roughly O(N^3/2).
  840. X */
  841. static void shellsort(p,index,n,tr)
  842. register blob **p;
  843. register blob *tr;
  844. register int index;
  845. register int n;
  846. X{
  847. X register blob ch;
  848. X register blob *s1;
  849. X register blob *s2;
  850. X register int incr;
  851. X register int *incrp;
  852. X register int t1;
  853. X register int t2;
  854. X
  855. X incrp = __rsshell_increments;
  856. X while (incr = *incrp++)
  857. X   for (t1 = incr;t1 < n;++t1)
  858. X     for (t2 = t1 - incr;t2 >= 0;)
  859. X      {
  860. X       s1 = p[t2] + index;
  861. X       s2 = p[t2 + incr] + index;
  862. X       while ((ch = tr[*s1++]) == tr[*s2] && ch)
  863. X         ++s2;
  864. X       if (ch > tr[*s2])
  865. X    {
  866. X         s1 = p[t2];
  867. X         p[t2] = p[t2 + incr];
  868. X         p[t2 + incr] = s1;
  869. X         t2 -= incr;
  870. X    }
  871. X       else
  872. X         break;
  873. X      }
  874. X}
  875. X
  876. X/* KB says:
  877. X * Stackp points to context structures, where each structure schedules a
  878. X * partitioning.  Radixsort exits when the stack is empty.
  879. X *
  880. X * If the buckets are placed on the stack randomly, the worst case is when
  881. X * all the buckets but one contain (npartitions + 1) elements and the bucket
  882. X * pushed on the stack last contains the rest of the elements.  In this case,
  883. X * stack growth is bounded by:
  884. X *
  885. X *    limit = (nelements / (npartitions + 1)) - 1;
  886. X *
  887. X * This is a very large number, 52,377,648 for the maximum 32-bit signed int.
  888. X *
  889. X * By forcing the largest bucket to be pushed on the stack first, the worst
  890. X * case is when all but two buckets each contain (npartitions + 1) elements,
  891. X * with the remaining elements split equally between the first and last
  892. X * buckets pushed on the stack.  In this case, stack growth is bounded when:
  893. X *
  894. X *    for (partition_cnt = 0; nelements > npartitions; ++partition_cnt)
  895. X *        nelements =
  896. X *            (nelements - (npartitions + 1) * (nbuckets - 2)) / 2;
  897. X *
  898. X * The bound is:
  899. X *
  900. X *    limit = partition_cnt * (nbuckets - 1);
  901. X *
  902. X * This is a much smaller number, 4590 for the maximum 32-bit signed int.
  903. X
  904. Note inserted by DJB: About time I proved this... Fix the number of
  905. buckets, b. Any given pile of n elements is split into m stack piles and
  906. b - m small-scale piles which immediately disappear. We ignore the case
  907. where the pile is split into only one pile of its original size---any
  908. pile will be split into smaller piles eventually. Say the stack is left
  909. with piles of sizes p_1 ... p_m, each at least P + 1, none equal to n,
  910. while x elements, for some x from 0 to m'P, are in small-scale piles.
  911. X(Here P is the cutoff.) We must have p_1 + ... + p_m + x = n. Depending
  912. on the other (p,x) constraints chosen, we define s(n) as the maximum
  913. stack size for n elements. As the subpile distributions are independent,
  914. clearly
  915. X
  916. X  s(n) = max_m max_(p,x) max {s(p_1),s(p_2) + 1,...,s(p_m) + m - 1}
  917. X
  918. over all valid m and (p,x). In particular, if m > 0 then we must have
  919. n > p_1 >= P + 1, so if n <= P + 1 then the maximum is (vacuously) 0. So
  920. s(n) is monotone increasing for n <= P + 1. An easy induction shows that
  921. s(n) is in fact 0 for all n < 2P + 2.
  922. X
  923. Clearly s(n) is monotone: for n >= P + 2 we choose m = 1, p_1 = n - 1,
  924. and x = 0, and we see s(n) >= s(p_1) = s(n - 1). For m = 0, the maximum
  925. always equals 0, and for m = 1, the maximum always equals a previous
  926. s(p_1), so we have
  927. X
  928. X  s(n) = max { max_{k<n} s(k) , max_{m>=2} max_(p,x) max s(p_j) + j - 1 }.
  929. X
  930. XFor convenience we define t(n) = max_{m>=2} max_(p,x) max s(p_j) + j - 1.
  931. X
  932. XFix n. Fix m >= 2. Consider a (p,x) achieving the maximum value of
  933. max s(p_j) + j - 1. Since p_1 >= P + 1, we have p_2 <= n - P - 1. If x
  934. isn't 0, we can move an element from one of the small-scale piles to
  935. stack pile p_2, under either of the constraints in question. This
  936. increases p_2---hence does not decrease s(p_2)---without affecting the
  937. other s(p_j). Hence there is a (p,x) with smaller x also achieving the
  938. maximum.
  939. X
  940. So consider a (p,0) achieving the maximum, and say max s(p_j) + j - 1 is
  941. achieved at j = i. If we exchange p_i and p_j while meeting the
  942. constraints, we must not be at a higher maximum; in particular,
  943. s(p_i) + j - 1 <= s(p_i) + i - 1, so j <= i.
  944. X
  945. Restrict attention the the case without constraints, NC. The choice of j
  946. is unrestricted, so in particular m <= i and hence i = m. Thus t(n)
  947. equals max_{m>=2} s(p_m) + m - 1. Since all p_j are at least P + 1, we
  948. have
  949. X
  950. X  p_m + (P + 1)(m - 1) <= p_m + ... + p_1 = n
  951. X  p_m <= n - (P + 1)(m - 1)
  952. X  s(p_m) <= s(n - (P + 1)(m - 1))
  953. X  t(n) <= max_{m>=2} s(n - (P + 1)(m - 1)) + m - 1    (NC),
  954. X
  955. and it is easy to see that for n >= (P + 1)m, we can choose p_m as
  956. n - (P + 1)(m - 1) >= P + 1 and all other p_j = P + 1, so that the bound
  957. is achieved:
  958. X
  959. X  t(n) = max_{m>=2} s(n - (P + 1)(m - 1)) + m - 1  for  n/(P + 1) >= m.  (NC)
  960. X
  961. XFor 2 <= n/(P + 1) < b, we can choose m anywhere between 2 and
  962. f = floor(n/(P + 1)) inclusive. Now
  963. X
  964. X  s(n) = max { max s(k), max_{2<=m<f} s(n - (P + 1)(m - 1)) + m - 1 } (NC)
  965. X
  966. We claim inductively that s(n) = f - 1 for any n with floor(n/(P + 1)) =
  967. f. This is true for f = 1. For larger f, s(n - (P + 1)(m - 1)) =
  968. floor((n - (P + 1)(m - 1))/(P + 1)) - 1 = f - (m - 1) - 1 = f - m, so
  969. that
  970. X
  971. X  s(n) = max { max s(k), f - 1 }   (NC)
  972. X
  973. If n = (P + 1)f, then by inductive hypothesis s(k) <= f - 2, so that
  974. s(n) = f - 1 as desired. Otherwise, by (sub)induction on n, s(k) is
  975. still bounded by f - 1, so that s(n) = f - 1 always. Therefore:
  976. X
  977. X  s(n) = floor(n/(P + 1)) - 1,  n >= P + 1.     (NC)
  978. X
  979. Now consider the push-largest-pile-first constraint, FC. This requires
  980. that p_1 >= p_j for all j. Hence we cannot swap p_1 with p_i. However,
  981. if i is not 1 then we can swap p_j with p_i for all j > 1, hence j <= i
  982. for all j between 2 and m, hence i is m. Thus the maximum is achieved
  983. either at i = 1 or at i = m, and we have
  984. X
  985. X  t(n) = max_{m>=2} max_(p,0) max { s(p_m) + m - 1, s(p_1) }.   (FC)
  986. X
  987. Take a p vector achieving the maximum of max { s(p_m) + m - 1, s(p_1) },
  988. with m fixed. Suppose some p_j for j between 2 and m - 1 inclusive is
  989. larger than P + 1. (This is vacuous for m = 2.) Then we can subtract one
  990. from p_j and add one to p_1, preserving the constraint and not
  991. decreasing the maximum. Hence the maximum is achieved somewhere with all
  992. p_j = P + 1 for 2 <= j < m, i.e.,
  993. X
  994. X  p_1 + p_m + (P + 1)(m - 2) = n.   (FC)
  995. X
  996. XFurthermore, p_1 >= p_m. Hence 2p_1 >= n - (P + 1)(m - 2), and p_1 can
  997. range from ceiling((n - (P + 1)(m - 2))/2) up to n - (P + 1). Similarly,
  998. X2p_m <= n - (P + 1)(m - 2), so p_m can range from P + 1 up to
  999. floor((n - (P + 1)(m - 2))/2). The global maximum of these quantities
  1000. simultaneously equals the global maximum of them individually, so if all
  1001. bounds can be achieved then
  1002. X
  1003. X  t(n) = max_{m>=2} max { s(n - (P + 1)),
  1004. X              s(floor((n - (P + 1)(m - 2))/2)) + m - 1 }.  (FC)
  1005. X
  1006. This can be achieved if n - (P + 1) >= ceiling((n - (P + 1)(m - 2))/2)
  1007. and, equivalently, P + 1 <= floor((n - (P + 1)(m - 2))/2), since in that
  1008. case we can choose both p_1 and p_m as stated. These reduce after some
  1009. simple manipulation to n >= (P + 1)m, i.e., m <= floor(n/(P + 1)). For
  1010. other m it is not possible to choose any valid p_i (exercise).
  1011. X
  1012. We'd like to show inductively that for all n >= 2P + 2 we have
  1013. X
  1014. X  s(n) = u(n) with
  1015. X  u(n) = max_{m>=2} s(floor((n - (P + 1)(m - 2))/2)) + m - 1.   (FC,*)
  1016. X
  1017. To do this we need only show that the other terms of the maximum do not
  1018. X``get in the way,'' i.e., that u(n) >= s(n - (P + 1)) and u(n) >= s(k)
  1019. for k < n. The second half is easy: s(k) = u(k), which is at most u(n)
  1020. by monotonicity of s. The first half also follows from the induction:
  1021. X
  1022. X  s(n) = max_m s(floor((n - (P + 1)(m - 2))/2)) + m - 1
  1023. X  s(n - (P + 1)) = u(n - (P + 1))
  1024. X   = max_{m>=2} s(floor((n - (P + 1) - (P + 1)(m - 2))/2)) + m - 1
  1025. X   <= max_{m>=2} s(floor((n - (P + 1)(m - 2))/2)) + m - 1
  1026. X   = u(n)                    (FC)
  1027. X
  1028. again by the monotonicity of s. This proves (FC,*). For small n, i.e.,
  1029. floor(n/(P + 1)) = f with 2 <= f <= b, we can choose m = f, so s(n) is
  1030. at least s(floor((n - (P + 1)(f - 2))/2)) + f - 1. The floor term is at
  1031. most P + 1, so s(n) >= f - 1. Furthermore, s in the constrained case is
  1032. at most s in the unconstrained case, so s(n) = f - 1. For larger n, by
  1033. similar logic, the maximum is attained at m = b, so we finally have
  1034. X
  1035. X  s(n) = floor(n/(P + 1)) - 1  for n < (b + 1)(P + 1)
  1036. X  s(n) = s(floor((n - (P + 1)(b - 2))/2)) + b - 1  otherwise    (FC)
  1037. X
  1038. As in the first case s(n) is always bounded by b - 1, we can calculate
  1039. a bound on s(n) by repeatedly setting n to floor(n - (P + 1)(b - 2))/2)
  1040. until it is under 2P + 2 (so that s(n) = 0), counting the number of
  1041. iterations necessary, and multiplying by b - 1. And that's what we
  1042. wanted to prove.
  1043. X*/
  1044. X
  1045. X#ifndef UCHAR_MAX /* XXX: we aren't even giving a chance for a definition! */
  1046. X#define UCHAR_MAX 256
  1047. X#endif
  1048. X#define    NBUCKETS (UCHAR_MAX + 1)
  1049. X
  1050. typedef struct
  1051. X {
  1052. X  blob **bot;
  1053. X  int index;
  1054. X  int n;
  1055. X }
  1056. context;
  1057. X
  1058. X#define    STACKPUSH { \
  1059. X  stackp->bot = p; \
  1060. X  stackp->n = n; \
  1061. X  stackp->index = index; \
  1062. X  ++stackp; \
  1063. X}
  1064. X
  1065. X#define    STACKPOP { \
  1066. X  if (stackp == stack) \
  1067. X    break; \
  1068. X  --stackp; \
  1069. X  bot = stackp->bot; \
  1070. X  n = stackp->n; \
  1071. X  index = stackp->index; \
  1072. X}
  1073. X
  1074. X/* KB says:
  1075. X * This uses a simple sort as soon as a bucket crosses a cutoff point,
  1076. X * rather than sorting the entire list after partitioning is finished.
  1077. X * This should be an advantage.
  1078. X
  1079. Note from DJB: The original comment read ``There is no strong evidence
  1080. that this is an advantage.'' Depressing. Here's what I wrote in response:
  1081. X
  1082. X   Of course it's an advantage: it has to be, I coded it that way. :-)
  1083. X   Seriously, I just coded the sort that way since I was following Knuth's
  1084. X   description of MSD to the hilt. As you can imagine, though, doing the
  1085. X   sort this way saves just a bit of paging of the index array. It also
  1086. X   means that the simple sort doesn't have to worry about crossing past
  1087. X   already-determined boundaries---for an average 2x gain. Trust me, it's
  1088. X   an advantage.
  1089. X*/
  1090. X
  1091. int radixsort7(l1,n,endchar,tab,indexstart,ralloc,rfree)
  1092. blob **l1;
  1093. register int n;
  1094. unsigned int endchar; /* could use blob, but chars are unsafe with prototypes */
  1095. blob *tab;
  1096. int indexstart;
  1097. char *(*ralloc)();
  1098. void (*rfree)();
  1099. X{
  1100. X register int i;
  1101. X register int index;
  1102. X register int t1;
  1103. X register int t2;
  1104. X register blob **l2;
  1105. X register blob **p;
  1106. X register blob **bot;
  1107. X register blob *tr;
  1108. X context *stack;
  1109. X context *stackp;
  1110. X static int c[NBUCKETS + 1];
  1111. X static int *ctr[NBUCKETS + 1];
  1112. X int max;
  1113. X blob ltab[NBUCKETS]; /* local (default) table */
  1114. X
  1115. X if (n <= 1)
  1116. X   return 0;
  1117. X
  1118. X /* Allocate the stack. */
  1119. X t1 = (__rspartition + 1) * (NBUCKETS - 2);
  1120. X for (i = 0,t2 = n;t2 > __rspartition;i += NBUCKETS - 1)
  1121. X   t2 = (t2 - t1)/2; /* could go negative! but that's okay */
  1122. X if (!i)
  1123. X   stack = stackp = 0;
  1124. X else
  1125. X   if (!(stack = stackp = (context *)ralloc(i * sizeof(context))))
  1126. X     return -1;
  1127. X
  1128. X /* KB says:
  1129. X  * There are two arrays, one provided by the user (l1), and the
  1130. X  * temporary one (l2). The data is sorted to the temporary stack,
  1131. X  * and then copied back. The speedup of using index to determine
  1132. X  * which stack the data is on and simply swapping stacks back and
  1133. X  * forth, thus avoiding the copy every iteration, turns out to not
  1134. X  * be any faster than the current implementation.
  1135. X  */
  1136. X if (!(l2 = (blob **)ralloc(n * sizeof(blob *))))
  1137. X  {
  1138. X   rfree((char *)stackp);
  1139. X   return -1;
  1140. X  }
  1141. X
  1142. X /* KB says:
  1143. X  * tr references a table of sort weights; multiple entries may
  1144. X  * map to the same weight; EOS char must have the lowest weight.
  1145. X  */
  1146. X if (tab)
  1147. X   tr = tab;
  1148. X else
  1149. X  {
  1150. X   t2 = endchar;
  1151. X   for (t1 = 0;t1 < t2;++t1)
  1152. X     ltab[t1] = t1 + 1;
  1153. X   ltab[t2] = 0;
  1154. X   for (t1 = t2 + 1;t1 < NBUCKETS;++t1)
  1155. X     ltab[t1] = t1;
  1156. X   tr = ltab;
  1157. X  }
  1158. X
  1159. X for (t1 = 0;t1 < NBUCKETS;++t1)
  1160. X   ctr[t1] = c + tr[t1];
  1161. X
  1162. X /* First sort is entire pile. */
  1163. X bot = l1;
  1164. X index = indexstart;
  1165. X
  1166. X for (;;)
  1167. X  {
  1168. X   /* Clear the bucket count array. XXX: This isn't portable to */
  1169. X   /* machines where the byte representation of int 0 isn't all */
  1170. X   /* zeros. :-) */
  1171. X   bzero((char *)c,sizeof(c));
  1172. X
  1173. X   /* Compute number of items that sort to the same bucket for this index. */
  1174. X   p = bot;
  1175. X   i = n;
  1176. X   while (--i >= 0)
  1177. X     ++*ctr[(*p++)[index]];
  1178. X
  1179. X   /* KB says:
  1180. X    * Sum the number of characters into c, dividing the temp stack
  1181. X    * into the right number of buckets for this bucket, this index.
  1182. X    * c contains the cumulative total of keys before and included in
  1183. X    * this bucket, and will later be used as an index to the bucket. 
  1184. X    * c[NBUCKETS] contains the total number of elements, for determining
  1185. X    * how many elements the last bucket contains. At the same time, we
  1186. X    * find the largest bucket so it gets pushed first.
  1187. X    */
  1188. X   t2 = __rspartition;
  1189. X   max = t1 = 0;
  1190. X   for (i = 0;i <= NBUCKETS;++i)
  1191. X    {
  1192. X     if (c[i] > t2)
  1193. X      {
  1194. X       t2 = c[i];
  1195. X       max = i;
  1196. X      }
  1197. X     t1 = c[i] += t1;
  1198. X    }
  1199. X
  1200. X   /* Partition the elements into buckets; c decrements through the */
  1201. X   /* bucket, and ends up pointing to the first element of the bucket. */
  1202. X   i = n;
  1203. X   while (--i >= 0)
  1204. X    {
  1205. X     --p;
  1206. X     l2[--*ctr[(*p)[index]]] = *p;
  1207. X    }
  1208. X
  1209. X   /* Copy the partitioned elements back to the user stack. */
  1210. X   bcopy(l2,bot,n * sizeof(blob *));
  1211. X
  1212. X   ++index;
  1213. X   /* KB says:
  1214. X    * Sort buckets as necessary; don't sort c[0], it's the
  1215. X    * EOS character bucket, and nothing can follow EOS.
  1216. X    */
  1217. X   for (i = max;i;--i)
  1218. X    {
  1219. X     if ((n = c[i + 1] - (t1 = c[i])) < 2)
  1220. X       continue;
  1221. X     p = bot + t1;
  1222. X     if (n > __rspartition)
  1223. X       STACKPUSH
  1224. X     else
  1225. X       shellsort(p,index,n,tr);
  1226. X    }
  1227. X   for (i = max + 1;i < NBUCKETS;++i)
  1228. X    {
  1229. X     if ((n = c[i + 1] - (t1 = c[i])) < 2)
  1230. X       continue;
  1231. X     p = bot + t1;
  1232. X     if (n > __rspartition)
  1233. X       STACKPUSH
  1234. X     else
  1235. X       shellsort(p,index,n,tr);
  1236. X    }
  1237. X   /* Break out when stack is empty */
  1238. X   STACKPOP
  1239. X  }
  1240. X
  1241. X rfree((char *)l2);
  1242. X rfree((char *)stack);
  1243. X return 0;
  1244. X}
  1245. X
  1246. extern char *malloc();
  1247. extern void free();
  1248. X
  1249. int radixsort5(l1,n,endchar,tab,indexstart)
  1250. blob **l1; register int n; unsigned int endchar; blob *tab; int indexstart;
  1251. X{
  1252. X return radixsort7(l1,n,endchar,tab,indexstart,malloc,free);
  1253. X}
  1254. X
  1255. int radixsort4(l1,n,endchar,tab)
  1256. blob **l1; register int n; unsigned int endchar; blob *tab;
  1257. X{
  1258. X return radixsort7(l1,n,endchar,tab,0,malloc,free);
  1259. X}
  1260. X
  1261. int radixsort(l1,n,tab,endchar)
  1262. blob **l1; register int n; blob *tab; unsigned int endchar;
  1263. X{
  1264. X return radixsort7(l1,n,endchar,tab,0,malloc,free);
  1265. X}
  1266. X
  1267. int radixsort3(l1,n,endchar)
  1268. blob **l1; register int n; unsigned int endchar; 
  1269. X{
  1270. X return radixsort7(l1,n,endchar,(blob *) 0,0,malloc,free);
  1271. X}
  1272. X
  1273. X/*- BSD copyright says:
  1274. X * Copyright (c) 1990 The Regents of the University of California.
  1275. X * All rights reserved.
  1276. X *
  1277. X * Redistribution and use in source and binary forms, with or without
  1278. X * modification, are permitted provided that the following conditions
  1279. X * are met:
  1280. X * 1. Redistributions of source code must retain the above copyright
  1281. X *    notice, this list of conditions and the following disclaimer.
  1282. X * 2. Redistributions in binary form must reproduce the above copyright
  1283. X *    notice, this list of conditions and the following disclaimer in the
  1284. X *    documentation and/or other materials provided with the distribution.
  1285. X * 3. All advertising materials mentioning features or use of this software
  1286. X *    must display the following acknowledgement:
  1287. X *    This product includes software developed by the University of
  1288. X *    California, Berkeley and its contributors.
  1289. X * 4. Neither the name of the University nor the names of its contributors
  1290. X *    may be used to endorse or promote products derived from this software
  1291. X *    without specific prior written permission.
  1292. X *
  1293. X * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  1294. X * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  1295. X * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  1296. X * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  1297. X * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  1298. X * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  1299. X * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  1300. X * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  1301. X * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  1302. X * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  1303. X * SUCH DAMAGE.
  1304. X */
  1305. X
  1306. X/* BSD sccs says:
  1307. static char sccsid[] = "@(#)radixsort.c  5.7 (Berkeley) 2/23/91";
  1308. X
  1309. but this is (heavily) modified.
  1310. X*/
  1311. END_OF_FILE
  1312. if test 20057 -ne `wc -c <'radixsort.c'`; then
  1313.     echo shar: \"'radixsort.c'\" unpacked with wrong size!
  1314. fi
  1315. # end of 'radixsort.c'
  1316. fi
  1317. echo shar: End of archive 8 \(of 9\).
  1318. cp /dev/null ark8isdone
  1319. MISSING=""
  1320. for I in 1 2 3 4 5 6 7 8 9 ; do
  1321.     if test ! -f ark${I}isdone ; then
  1322.     MISSING="${MISSING} ${I}"
  1323.     fi
  1324. done
  1325. if test "${MISSING}" = "" ; then
  1326.     echo You have unpacked all 9 archives.
  1327.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1328. else
  1329.     echo You still need to unpack the following archives:
  1330.     echo "        " ${MISSING}
  1331. fi
  1332. ##  End of shell archive.
  1333. exit 0
  1334.